package com.kuang.blog.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.kuang.blog.entity.User;
import com.kuang.blog.service.UserService;
import com.kuang.blog.util.JwtUtils;
import com.kuang.blog.util.Result;
import io.jsonwebtoken.Jwts;
import jdk.nashorn.internal.runtime.options.Option;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.Optional;

@RestController
public class LoginController {
    @Resource
    private JwtUtils jwtUtils;
    @Resource
    private UserService userService;
    @PostMapping("/login")
    public Result login(@RequestBody User user, HttpServletResponse response){
        //创建条件
        QueryWrapper<User> wrapper = new QueryWrapper<User>();
        wrapper.eq("username",user.getUsername());
        //错误情况
        User one = userService.getOne(wrapper);
        if (one==null){
            return Result.fail("用户名不存在");
        }
        if (!one.getPassword().equals(user.getPassword())){
            return Result.fail("密码不正确");
        }
        //正常情况

        String token = jwtUtils.jwtEncrypt(one);
        //正确未登录
        return Result.success(200,"登录成功！",token);
    }

    @GetMapping("/logout")
    @RequiresAuthentication
    public Result logout(){
        System.out.println("退出成功");
        SecurityUtils.getSubject().logout();
        return Result.success(200);
    }
}
